package com.uam.web.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;


import com.uam.common.annotation.Log;
import com.uam.db.model.bo.UserBo;
import com.uam.db.model.entity.User;

import com.uam.db.model.vo.UserListVO;
import com.uam.service.UserListService;
import com.uam.service.UserService;

import com.uam.utils.RedisUtil;

import com.uam.web.common.model.BusinessType;
import com.uam.web.common.model.PageRes;
import com.uam.web.common.model.Result;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author GoryLee
 * @Date 2022/12/5 00:51
 * @Version 1.0
 */
@Api(tags = "用户操作")
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserService userService;
    @Autowired
    private UserListService userListService;
    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/getUser")
    @PreAuthorize("@customExpression.hasAuthority('sys:admin')")
    public Result<User> getUser(UserBo query) {
        User user = userService.getUser(query);
        return Result.createSuccess(user);
    }


    @ApiOperation(value = "用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loginName", value = "登录名", dataTypeClass = String.class),
            @ApiImplicitParam(name = "password", value = "密码", dataTypeClass = String.class)
    })
    @PostMapping("/login")
    public Result login(@RequestParam(required = true) String loginName,
                        @RequestParam(required = true) String password) {
        return userListService.login(loginName, password);
    }

    @ApiOperation(value = "用户注销")
    //  @Log(title = "操作日志列表", businessType = BusinessType.QUERY_LIST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户登录token", paramType = "header")
    })
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {

      /*  UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();
        redisUtil.del("login:" + user.getUserId());*/
        return userListService.logout(request);
       // return Result.createSuccess("注销成功");
    }

    @Log(title = "查看用户列表", businessType = BusinessType.QUERY_LOG)
    @ApiOperation(value = "用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户登录token", paramType = "header"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "Integer", defaultValue = "0", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "pageSize", value = "分页条数", dataType = "Integer", defaultValue = "10", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "roleName", value = "用户角色，例：管理员、教师、学生", dataTypeClass = String.class),
            @ApiImplicitParam(name = "loginName", value = "登录名", dataTypeClass = String.class),
            @ApiImplicitParam(name = "userName", value = "姓名/用户名", dataTypeClass = String.class),
            @ApiImplicitParam(name = "studentNumber", value = "学号", dataTypeClass = String.class),
    })
    @PostMapping("/list")
    @PreAuthorize("@customExpression.hasAuthority('sys:user:list')")
    @ResponseBody
    public Result list(@RequestParam(required = false, defaultValue = "0") Integer pageNum,
                       @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false) List<String> roleName,
                       @RequestParam(required = false) String loginName,
                       @RequestParam(required = false) String userName,
                       @RequestParam(required = false) String studentNumber) {
        IPage<UserListVO> pageResult = userListService.selectUesrList(pageNum,
                pageSize,
                roleName,
                loginName,
                userName,
                studentNumber);
        PageRes<UserListVO> userListVOPageRes = new PageRes<>(pageResult.getRecords(), pageResult.getTotal());
        return Result.createSuccess(userListVOPageRes);
    }

    @Log(title = "编辑账号")
    @ApiOperation(value = "编辑")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户登录token", paramType = "header"),
            @ApiImplicitParam(name = "password", value = "密码"),
            @ApiImplicitParam(name = "roleName", value = "角色名称"),
            @ApiImplicitParam(name = "loginName", value = "登录名"),
            @ApiImplicitParam(name = "userName", value = "用户名/姓名"),
            @ApiImplicitParam(name = "studentNumner", value = "学号"),
            @ApiImplicitParam(name = "userId", value = "被编辑的用户ID，如果不穿默认修改token对应id"),
    })
    @PostMapping("/edit")
    @PreAuthorize("@customExpression.hasAuthority('sys:user:edit')")
    @ResponseBody
    public Result editUser(HttpServletRequest request,
                           @RequestParam(required = false) String password,
                           @RequestParam(required = false) String roleName,
                           @RequestParam(required = false) String loginName,
                           @RequestParam(required = false) String userName,
                           @RequestParam(required = false) String studentNumber,
                           @RequestParam(required = false) Long userId
    ) {
        return userListService.editUser(request, password, roleName, loginName, userName, studentNumber, userId);
    }

    @Log(title = "删除账号")
    @ApiOperation(value = "删除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户登录token", paramType = "header"),
            @ApiImplicitParam(name = "userIds", value = "用户名，如果超级管理员修改别人密码时需传参，修改自己密码可不传",dataTypeClass = List.class),
    })
    @PostMapping("/delete")
    @PreAuthorize("@customExpression.hasAuthority('sys:user:delete')")
    @ResponseBody
    public Result deleteUser(HttpServletRequest request,
                             @RequestParam(required = false) List<Long> userIds
    ) {
        return userListService.deleteUserByUserIds(request, userIds);
    }

    @Log(title = "添加账号")
    @ApiOperation(value = "新增用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "用户登录token", paramType = "header", required = true),
            @ApiImplicitParam(name = "userId", value = "不需要传,自动生成"),
            @ApiImplicitParam(name = "loginName", value = "登录名"),
            @ApiImplicitParam(name = "userName", value = "用户名/姓名"),
            @ApiImplicitParam(name = "studentNumner", value = "学号"),
            @ApiImplicitParam(name = "roleName", value = "角色名称"),
            @ApiImplicitParam(name = "password", value = "密码")
    })
    @PostMapping("/add")
    @PreAuthorize("@customExpression.hasAuthority('sys:user:add')")
    @ResponseBody
    public Result add(HttpServletRequest request,
                      @RequestParam(required = false) Long userId,
                      @RequestParam(required = true) String loginName,
                      @RequestParam(required = false) String userName,
                      @RequestParam(required = false) String studentNumner,
                      @RequestParam(required = true) String roleName,
                      @RequestParam(required = false) String password

    ) {

        return userListService.addUser(userId, loginName, userName, studentNumner, roleName, password);
    }

}
